<template>
  <el-dialog
    :title="dialogProps.title"
    :visible.sync="dialogProps.visible"
    width="600px"
    @open="handleDialogOpen()"
    v-loading="loading"
  >
    <div slot="title" class="dialog-header">{{ dialogProps.title }}</div>
    <el-form
      :model="appointmentModel"
      ref="appointmentForm"
      label-width="80px"
      label-position="right"
      size="small"
    >
      <el-tabs type="border-card" v-model="activeTabName">
        <el-tab-pane name="appointmentTab" label="基本信息" class="user-info-tab-pane">
          <el-form-item label="身份证号" prop="idcard">
            <el-col :span="16">
              <el-autocomplete
                style="width:270px"
                v-model="appointmentModel.idcard"
                :fetch-suggestions="querySearch"
                @select="handleSelect"
              ></el-autocomplete>
            </el-col>
          </el-form-item>
          <el-form-item label="预约日期" prop="time">
            <el-col :span="16">
              <el-date-picker
                v-model="appointmentModel.time"
                type="date"
                :picker-options="pickerOptions"
                style="width:270px"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-col :span="16">
              <el-input v-model="appointmentModel.name" :disabled="true"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="性别" prop="sex" disabled>
            <el-col :span="16">
              <!-- <el-radio-group v-model="appointmentModel.sex">
                <el-radio label="0">男</el-radio>
                <el-radio label="1">女</el-radio>
              </el-radio-group> -->
              <el-input v-model="appointmentModel.sex" :disabled="true"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-col :span="16">
              <el-input :length="11" v-model="appointmentModel.phone" :disabled="true"></el-input>
            </el-col>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="套餐信息">
          <!-- <el-input placeholder="检查项目名" size="small" style="width:260px" v-model="search.name">
        <el-col :span="12">
            <el-button slot="append" icon="el-icon-search" @click="searchCombo"></el-button>
        </el-col>
          </el-input>-->
          <el-row>
            <el-col :span="24">
              <el-table
                ref="itsmDataTable"
                :data="comboList"
                border
                size="mini"
                header-cell-class-name="header-row"
                height="300"
              >
                <el-table-column type="selection" width="40"></el-table-column>
                <el-table-column
                  prop="name"
                  label="套餐名"
                  align="center"
                  header-align="center"
                  width="200px"
                ></el-table-column>
                <el-table-column
                  prop="sex"
                  label="适用性别"
                  :formatter="formatterSex"
                  header-align="center"
                  align="center"
                  width="90px"
                ></el-table-column>
                <el-table-column
                  label="适用年龄"
                  :formatter="formatterAge"
                  header-align="center"
                  align="center"
                  width="90px"
                ></el-table-column>
                <el-table-column
                  prop="price"
                  label="套餐价格"
                  header-align="center"
                  align="center"
                  width="90px"
                ></el-table-column>
                <el-table-column
                  prop="remark"
                  label="套餐介绍"
                  header-align="center"
                  align="center"
                  width="250px"
                ></el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleDialogClose()">取 消</el-button>
      <el-button type="primary" size="small" @click="submitForm('appointmentForm')">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { saveAppointment, updateAppointment } from "@/api/dingming/appointment";

export default {
  name: "appointment-edit",
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      loading: false,
      appointmentModel: {
        id: 0,
        memberId: "",
        setmealId: "",
        name: "",
        sex: "",
        phone: "",
        idcard: "",
        time: "",
        updatetime: "",
        orderId: "",
        tOrder: {
          id: 0,
          memberId: "",
          orderdate: "",
          orderstatus: 0,
          setmealId: "",
          createtime: "",
          updatetime: ""
        }
      },
      dialogProps: {
        visible: false,
        action: "",
        title: ""
      },
      activeTabName: "appointmentTab",
      memberList: [],
      comboList: []
    };
  },
  methods: {
    /**
     * 返回输入建议
     */
    querySearch(queryString, cb) {
      var idCards = [];
      for (var member of this.memberList) {
        idCards.push({ value: member.idcard, object: member });
      }
      var results = queryString
        ? idCards.filter(this.createFilter(queryString))
        : idCards;
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    /**
     *选择选项建议后显示相关信息
     */
    handleSelect(item) {
      this.appointmentModel.name = item.object.name;
      this.appointmentModel.sex = item.object.sex;
      this.appointmentModel.phone = item.object.phonenumber;
      this.appointmentModel.memberId = item.object.id;
      this.appointmentModel.tOrder.memberId=item.object.id;
    },
    /**
     * 点击确定按钮后判断是添加还是修改
     */
    submitForm(formName) {
      const selectData = this.$refs.itsmDataTable.selection;
      console.log(selectData)
      const comboIds = [];
      for (var data of selectData) {
        comboIds.push(data.id);
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.dialogProps.action === "add") {
            this.doSaveAppointment(comboIds);
          } else {
            this.doUpdateAppointment();
          }
        } else {
          return false;
        }
      });
    },
    /**
     * 修改的提交方法
     */
    doUpdateAppointment() {
      this.loading = true;
      updateAppointment(this.appointmentModel)
        .then(response => {
          this.loading = false;
          this.dialogProps.visible = false;
          this.$emit("save-finished");
        })
        .catch(error => {
          this.outputError(error);
        });
    },
    /**
     * 添加的提交方法
     */
    doSaveAppointment(comboIds) {
      this.loading = true;
      saveAppointment(this.appointmentModel,comboIds)
        .then(response => {
          this.loading = false;
          this.dialogProps.visible = false;
          this.$emit("save-finished");
        })
        .catch(error => {
          this.outputError(error);
        });
    },
    /**
     * 点击取消按钮
     */
    handleDialogClose() {
      this.dialogProps.visible = false;
    },
    /**
     * 弹框时触发的函数
     * 用来清除表单验证
     */
    handleDialogOpen() {
      /* this.$nextTick(() => {
        this.$refs["appointmentForm"].clearValidate();
      }); */
    },

    /*处理数据显示*/
    formatterSex(row, column) {
      if (row.sex == 2) {
        return "男";
      } else if (row.sex == 1) {
        return "女";
      }
      return "不限";
    },
    formatterAge(row, column) {
      if (row.minage == 0 && row.maxage == 100) {
        return "不限";
      }
      return row.minage + "-" + row.maxage;
    },

    /**
     * 错误提示
     */
    outputError(error) {
      console.log(error.response ? error.response : error.message);
      this.loading = false;
      this.$message({
        showClose: true,
        message: "出错了，请按F12查看浏览器日志。",
        type: "error"
      });
    }
  },
  /**
   * 传入父组件的方法
   * 用来判断用户点击的按钮是删除还是添加
   */
  mounted: function() {
    this.$nextTick(() => {
      this.$on("openEditAppointmentDialog", function(appointment) {
        /* this.appointmentModel = appointment;
        this.dialogProps.action = "edit";
        this.dialogProps.title = "编辑";
        this.dialogProps.visible = true; */
      }),
        this.$on("openAddAppointmentDialog", function(members, combo) {
          this.comboList = combo;
          this.memberList = members;
          this.dialogProps.action = "add";
          this.dialogProps.title = "预约";
          this.dialogProps.visible = true;
        });
    });
  }
};
</script>

<style lang="scss" scoped>
.user-info-tab-pane {
  margin-top: 10px;
}
</style>